package com.hjlh.aimedical.controller;

import com.hjlh.aimedical.common.respone.ResultModel;
import com.hjlh.aimedical.common.utils.CommonUtils;
import com.hjlh.aimedical.dao.UserDao;
import com.hjlh.aimedical.entity.User;
import com.hjlh.aimedical.model.UserModel;
import com.hjlh.aimedical.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Resource
    UserDao userDao;

    @GetMapping("queryUserByPhone")
    public User queryUserByPhone(String phone) {
     return   userDao.findByPhone(phone);
    }

    @RequestMapping("add")
    public ResultModel add(@RequestBody User user){
        return userService.add(user);
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResultModel login(@RequestBody UserModel userModel,
                             HttpSession httpSession){

        if(StringUtils.isEmpty(userModel.getPhone()) || StringUtils.isEmpty(userModel.getPassword())){
            return ResultModel.fail("请输入正确的账号和密码",null);
        }
        User user = userService.findByPhone(userModel.getPhone());
        UserModel model = new UserModel();
        if(user==null){
            return ResultModel.fail("请输入正确的账号和密码",null);
        }
        if(!CommonUtils.GetMD5Code(userModel.getPassword()).equals(user.getPassword())){
            return ResultModel.fail("请输入正确的账号和密码",null);
        }
        BeanUtils.copyProperties(user,model);
        model.setPassword(null);
        httpSession.setAttribute("userModel", model);
/*        @SuppressWarnings("unused")
        UserModel m = (UserModel) httpSession.getAttribute("userModel");
        logger.info("用户的sessionid是：{},session内容是：{}", httpSession.getId(), JSON.toJSONString(m));
        redisTemplate.opsForValue().set(httpSession.getId(),m,7200, TimeUnit.SECONDS);*/
        return ResultModel.success("登录成功",model);
    }

    @RequestMapping("/register")
    @ResponseBody
    public ResultModel register(@RequestBody UserModel userModel) {
        return userService.register(userModel);
    }
}
